# 安装所需库（如果未安装）
# !pip install gensim numpy

import gensim.downloader as api
from gensim.models import KeyedVectors
import numpy as np
import time


# 方法1：自动下载小型预训练模型（约65MB）
def demo_with_small_model():
    print("正在加载小型预训练模型...")
    start = time.time()

    # 下载并加载glove-twitter-25模型（小型词向量）
    model = api.load("glove-twitter-25")

    print(f"模型加载完成. 耗时: {time.time() - start:.2f}秒")
    print(f"词汇表大小: {len(model)}")

    # 示例1：查找相似词
    print("\n[相似词查询]")
    for word, score in model.most_similar("king", topn=5):
        print(f"{word}: {score:.4f}")

    # 示例2：计算词语相似度
    print("\n[词语相似度]")
    print(f"woman vs man: {model.similarity('woman', 'man'):.4f}")
    print(f"apple vs orange: {model.similarity('apple', 'orange'):.4f}")
    print(f"computer vs banana: {model.similarity('computer', 'banana'):.4f}")

    # 示例3：词向量加减计算（国王 - 男人 + 女人 = 女王）
    print("\n[向量运算]")
    result = model.most_similar(positive=['king', 'woman'], negative=['man'], topn=3)
    for word, score in result:
        print(f"{word}: {score:.4f}")


# 方法2：加载大型Google News模型（需要提前下载）
def demo_with_google_news_model(model_path):
    print("\n正在加载Google News模型...")
    start = time.time()

    # 加载二进制模型文件（需3-5分钟）
    model = KeyedVectors.load_word2vec_format(model_path, binary=True)

    print(f"模型加载完成. 耗时: {time.time() - start:.2f}秒")
    print(f"词汇表大小: {len(model)}")

    # 示例：查找相似词
    print("\n[高级相似词查询]")
    for word, score in model.most_similar("neural", topn=5):
        print(f"{word}: {score:.4f}")

    # 示例：找出不匹配的词
    print("\n[不匹配词检测]")
    print(model.doesnt_match(["breakfast", "cereal", "dinner", "lunch"]))


if __name__ == "__main__":
    # 使用小型模型快速演示
    demo_with_small_model()

    '''
    # 使用Google News模型（需提前下载）
    # 从以下链接下载模型文件（约1.6GB）：
    # https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM
    # google_model_path = "GoogleNews-vectors-negative300.bin.gz"
    # demo_with_google_news_model(google_model_path)
    '''